package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author: qingtao
 * @Date 2022/3/10 14:46
 */
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired(required = false)
    private DishService dishService;

    @Autowired(required = false)
    private HttpSession session;

    /**
     * 获得session
     * @return
     */
    public Long getUserId(){
        return  (Long)session.getAttribute("employee");
    }

    @PostMapping
    public R<String> saveWithFlavor(@RequestBody DishDto dishDto){
        System.out.println(dishDto);
        dishDto.setCreateUser(getUserId());
        dishDto.setUpdateUser(getUserId());
        dishService.saveWithFlavor(dishDto);
        return R.success("添加成功");
    }

    /**
     * 分页查询
     * （多表）
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
//    @GetMapping("/page")
    public R<Page<DishDto>> findAllByName1(Integer page, Integer pageSize, String name){
        Page<DishDto> dishDtoPage = dishService.findAllByName1(page, pageSize, name);
        return R.success(dishDtoPage);
    }


    /**
     * 分页查询 (连表)
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDto>> findAllByName2(Integer page, Integer pageSize, String name){
        Page<DishDto> dishDtoPage = dishService.findAllByName2(page, pageSize, name);
        return R.success(dishDtoPage);
    }


    /**
     * 根据Id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> findById(@PathVariable Long id){
        DishDto dishDto = dishService.findByID(id);
        return R.success(dishDto);
    }

    /**
     * 修改
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.update(dishDto, getUserId());
        return R.success("添加成功");
    }

    /**
     * 改状态（停售和启售）
     *
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status,@RequestParam("ids") Long[] ids){
        dishService.updateStatus(status,ids);
        return R.success("修改成功");
    }

    /**
     * 根据菜品类别的id查找的菜品
     * @param categoryId
     * @param status
     * @return
     */
    @RequestMapping("/list")
    public R<List<DishDto>> findByCategoryId(Long categoryId,@RequestParam(defaultValue = "1") Integer status){
        return R.success(dishService.findByCategoryId(categoryId,status));
    }
}
